package winOrDie.Application;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.w3c.dom.Document;

import winOrDie.Configuration.WoD_Configuration_Manager;
import winOrDie.Game.WoD_Game;
import winOrDie.Game.WoD_Game_Manager;
import winOrDie.Game.WoD_Game_Manager_Event;
import winOrDie.Game.WoD_Game_Manager_Listener;
import winOrDie.GameEngine.RT.mp.MapBoard;
import winOrDie.GameEngine.RT.mp.MapGenerator;
import winOrDie.GameEngine.RT.mp.WoD_MapBoard_Event;
import winOrDie.GameEngine.RT.mp.WoD_MapBoard_Listener;
import winOrDie.Net.WoD_Net_Protocol_Manager;
import winOrDie.Net.Client.WoD_Client_RT;
import winOrDie.Net.Client.WoD_Peer;
import winOrDie.Net.Client.WoD_Peers_List;
import winOrDie.Net.Http.httpmsg.WoD_HttpMessage;
import winOrDie.Net.Http.httpmsg.WoD_InfoJugadoresPartida;
import winOrDie.Net.Http.httpmsg.WoD_InfoPartidasActuales;
import winOrDie.Net.P2P.WoD_ScribeContent;
import winOrDie.Sound.Music.PlaySoundStream;
import winOrDie.Util.XML_Manager;
import winOrDie.graphicsInterface.GameMenu.Composite_Configuration_Event;
import winOrDie.graphicsInterface.GameMenu.Composite_Configuration_Listener;
import winOrDie.graphicsInterface.GameMenu.Composite_GameMenu;
import winOrDie.graphicsInterface.GameMenu.Composite_Join_Game_Event;
import winOrDie.graphicsInterface.GameMenu.Composite_Join_Game_Listener;
import winOrDie.graphicsInterface.GameMenu.Composite_List_Games_Event;
import winOrDie.graphicsInterface.GameMenu.Composite_List_Games_Listener;
import winOrDie.graphicsInterface.GameMenu.Composite_New_Game_Event;
import winOrDie.graphicsInterface.GameMenu.Composite_New_Game_Listener;
import winOrDie.graphicsInterface.GameRoom.Composite_GameRoom;
import winOrDie.graphicsInterface.GameRoom.Composite_Options_Event;
import winOrDie.graphicsInterface.GameRoom.Composite_Options_Listener;
import winOrDie.graphicsInterface.Login.Composite_Login;
import winOrDie.graphicsInterface.Login.Composite_Login_Event;
import winOrDie.graphicsInterface.Login.Composite_Login_Listener;
import winOrDie.graphicsInterface.RT.Composite_RT_Game;
import winOrDie.graphicsInterface.RT.Shell_RT_Game;

public class WoD_Application 
implements Composite_Login_Listener,
Composite_New_Game_Listener, 
Composite_Options_Listener, 
Composite_Configuration_Listener, 
Composite_Join_Game_Listener, 
Composite_List_Games_Listener, 
WoD_MapBoard_Listener
{

	private WoD_Application_Data woDApplicationData = null;
	
	private Display display = null;
	private Shell shell = null;
	
	private Composite_Login compositeLogin = null;

	private Composite_GameMenu compositeGameMenu = null;
	private Composite_GameRoom compositeGameRoom = null;
	
	private MapBoard mapBoard = null;
	
	
	private WoD_Game_Manager woDGameManager = null;
	
	private WoD_Net_Protocol_Manager woDNetProtocolManager = null;
	

	public static String Configuration_Filename = "WoD_Configuration.xml";
	
	
	private Composite_RT_Game compositeRTGame = null;
	
	
	public WoD_Application() {
		super();
		
		woDApplicationData = new WoD_Application_Data();
		woDNetProtocolManager = new WoD_Net_Protocol_Manager();
		initialice();
	}
	
	public WoD_Application(String configuration_File)
	{
		super();
		
		woDApplicationData = new WoD_Application_Data();
		
		Configuration_Filename = configuration_File;
		
		initialice();
		
	}
	
	/**
	 * Shows error message
	 * @param error
	 */
	private void show_Error(String error)
	{
		MessageBox messageBox = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
		messageBox.setText("Error");
		messageBox.setMessage(error);
		messageBox.open();
	}
	
	/**
	 * Shows error message
	 * @param error
	 */
	private void show_Info(String message)
	{
		MessageBox messageBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
		messageBox.setText("Información");
		messageBox.setMessage(message);
		messageBox.open();
	}
	
	
	/**
	 * Load configuration
	 */
	private void load_Configuration()
	{
		try {
			woDApplicationData.setWoDConfiguration(
					WoD_Configuration_Manager.get_WoD_Configuration_From_File(Configuration_Filename)
					);
		} catch (Exception e) {
			show_Error(e.getMessage());
			shell.dispose();
			
		}
	}
	
	private void initialice(){
		display = new Display();
		shell = new Shell(display,SWT.MIN | SWT.RESIZE);

		//shell.setLayout(new FillLayout());//Para que tome todo el espacio disponible
		shell.setText("Win or Die");
		
//		GridLayout gridLayout = new GridLayout();
//		gridLayout.numColumns = 1;
//		shell.setLayout(gridLayout);
		
		shell.setLayout(new FillLayout());


		show_Login();
		
	}
	
	public void execute()
	{
		//shell.pack();
		shell.open();
		
		load_Configuration();
		
		
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}

		}
		shell.dispose();
		System.exit(0);
	}
	
	private void show_Login()
	{
		shell.setSize(new Point(340, 200));
		woDApplicationData.setState(WoD_Application_Data.State.LOGIN);
		get_Composite_Login();
	}
	
	public Composite_Login get_Composite_Login()
	{
		if (compositeLogin == null)
		{
			GridData gridData = new GridData();
			gridData.grabExcessHorizontalSpace = true;
			gridData.grabExcessVerticalSpace = true;
			gridData.horizontalAlignment = SWT.CENTER;
			gridData.verticalAlignment = SWT.CENTER;
			
			compositeLogin = new Composite_Login(shell, SWT.NONE);
			compositeLogin.setLayoutData(gridData);
			
			compositeLogin.add_Composite_Login_Listener(this);
		}
		
		return compositeLogin;
	}
	
	
	
	@Override
	public void on_Composite_Login_Event(Composite_Login_Event event) {
		switch (event.getEventType()) {
		case Composite_Login_Event.Event_Types.LAN:
			
			woDApplicationData.setWoDPlayerData(
					get_Composite_Login().get_WoD_Player_Data()
					);
			
			get_Composite_Login().dispose();
			compositeLogin = null;
			woDApplicationData.setMode(WoD_Application_Data.Mode.LAN);
			show_GameMenu();
			set_ShowMode(display);
			
			break;

		case Composite_Login_Event.Event_Types.LOGIN:
			
			woDApplicationData.setWoDPlayerData(
					get_Composite_Login().get_WoD_Player_Data()
					);
			
			WoD_Login_Manager wod_login_manager = new WoD_Login_Manager();
			
			if(wod_login_manager.getLoginResult(get_Composite_Login().get_WoD_Player_Data(), woDApplicationData.getWoDConfiguration()))
			{
				woDApplicationData.setMode(WoD_Application_Data.Mode.WAN);
				System.out.println("\nLOGIN CORRECTE!!!!; USERNAME: " + get_Composite_Login().get_WoD_Player_Data().getUserName() + " PWD: " + get_Composite_Login().get_WoD_Player_Data().getUserPassword());
				get_Composite_Login().dispose();
				compositeLogin = null;
				show_GameMenu();
				set_ShowMode(display);
			}else
			{
				System.out.println("\nLOGIN INCORRECTE!!!!; USERNAME: " + get_Composite_Login().get_WoD_Player_Data().getUserName() + " PWD: " + get_Composite_Login().get_WoD_Player_Data().getUserPassword());
				show_Error("Login incorrecto.");
			}

			break;
			
		default:
			break;
		}
		
	}
	
	
	
	private void show_GameMenu()
	{
		get_Composite_GameMenu();
		
		/**
		 * Load configuration
		 */
		get_Composite_GameMenu()
			.get_Composite_Configuration()
				.setWoDConfiguration(
						woDApplicationData.getWoDConfiguration());
		
		
		
		shell.setSize(new Point(400, 400));
		woDApplicationData.setState(WoD_Application_Data.State.GAME_MENU);
	}
	
	public Composite_GameMenu get_Composite_GameMenu()
	{
		if (compositeGameMenu == null)
		{
			
			GridData gridData = new GridData();
			gridData.grabExcessHorizontalSpace = true;
			gridData.grabExcessVerticalSpace = true;
			gridData.horizontalAlignment = SWT.CENTER;
			gridData.verticalAlignment = SWT.CENTER;
			compositeGameMenu = new Composite_GameMenu(shell, SWT.NONE, woDApplicationData.getWoDConfiguration());
			compositeGameMenu.setLayoutData(gridData);
			
			/**
			 * New Game menu listener
			 */
			compositeGameMenu.get_Composite_New_Game().add_Composite_New_Game_Listener(this);
			
			/**
			 * Join Game menu listener
			 */
			compositeGameMenu.get_Composite_Join_Game().add_Composite_Join_Game_Listener(this);
			
			/**
			 * Configuration menu listener
			 */
			compositeGameMenu.get_Composite_Configuration().add_Composite_Configuration_Listener(this);
			
			/*
			 * Join game from Games List
			 * */
			compositeGameMenu.get_composite_List_Games().add_Composite_List_Games_Listener(this);
			
		}
				
		return compositeGameMenu;
	}
	
	
	public void onComposite_New_Game_Change(Composite_New_Game_Event event) 
	{
		switch (event.getEventType()) {
		case Composite_New_Game_Event.Event_Types.ACCEPT:
			
			woDApplicationData.setWoDGame(
					get_Composite_GameMenu().get_Composite_New_Game().getWoDGame()
					);
			
//			compositeGameMenu.dispose();
//			compositeGameMenu = null;
			

			/**
			 * Assign local address and port
			 */
			String host_Local = null;
			try {
				host_Local = InetAddress.getLocalHost().getHostAddress();
			} catch (UnknownHostException e) {
				show_Error(e.getMessage());
				break;
			}
			
			woDApplicationData.getWoDGame().setServerHost(host_Local);
			woDApplicationData.getWoDGame().setServer_port(
					woDApplicationData.getWoDConfiguration().getControl_Port()
					);
			
			//ENVIAMOS MENSAJE AL SERVIDOR WEB
			
			if(woDApplicationData.getMode() == WoD_Application_Data.Mode.WAN)
			{
				WoD_Game wodgame = woDApplicationData.getWoDGame();
				
				try {
						get_Composite_GameMenu().get_Composite_New_Game().send_Http_Message(
								woDApplicationData.getWoDConfiguration().getWeb_Server(),
								woDApplicationData.getWoDConfiguration().getWeb_Server_Port(), 
								woDApplicationData.getWoDPlayerData().getUserName(), wodgame.getServerHost(), 
								String.valueOf(wodgame.getServer_port()), wodgame.getGame_Title());
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						show_Error("HTTP error connection.");
				}				
			}
			
			
			//System.out.println("GAME ID" + get_Composite_GameMenu().get_Composite_New_Game().getWoDGame().getID_Game());
			compositeGameMenu.dispose();
			compositeGameMenu = null;
			get_Composite_GameRoom(this);
			shell.setSize(new Point(500, 460));
			woDApplicationData.setState(WoD_Application_Data.State.GAME_ROOM);
			
			try {
				/**
				 * Create new WoD_Game_Manager
				 */
				woDGameManager = new WoD_Game_Manager(woDApplicationData, compositeGameRoom);
				
					
			} catch (Exception e) {
				show_Error(e.getMessage());
			}
			
			break;

		default:
			break;
		}
	}
	
	@Override
	public void on_Composite_Join_Game_Changed(Composite_Join_Game_Event event) {
		switch (event.getEventType()) {
		case Composite_Join_Game_Event.Event_Types.CONNECT:
			
			woDApplicationData.setWoDGame(new WoD_Game());
			woDApplicationData.getWoDGame().setServerHost(
					compositeGameMenu
						.get_Composite_Join_Game()
							.get_Text_Peer_Direction()
								.getText()
					);
			
			woDApplicationData.getWoDGame().setServer_port(
					Integer.valueOf(					
						compositeGameMenu
							.get_Composite_Join_Game()
								.get_Text_Peer_Port()
									.getText())
					);
			
			
			
			compositeGameMenu.dispose();
			compositeGameMenu = null;
			
			get_Composite_GameRoom(this);
			shell.setSize(new Point(500, 460));
			woDApplicationData.setState(WoD_Application_Data.State.GAME_ROOM);
			
			try {
				woDGameManager = new WoD_Game_Manager(woDApplicationData, compositeGameRoom);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			break;

		default:
			break;
		}
	}
	

	@Override
	public void on_Composite_Configuration_Change(Composite_Configuration_Event event) 
	{
		switch (event.getEventType()) {
		case Composite_Configuration_Event.Event_Types.SAVE:
			
			try {
				if(woDApplicationData.getMode() == WoD_Application_Data.Mode.WAN)
				{
					if(WoD_HttpMessage.CheckWebServerConnection(
							get_Composite_GameMenu().get_Composite_Configuration().getWoDConfiguration().getWeb_Server(), 
							get_Composite_GameMenu().get_Composite_Configuration().getWoDConfiguration().getWeb_Server_Port()))
					{					
						woDApplicationData.setWoDConfiguration(
								get_Composite_GameMenu()
									.get_Composite_Configuration()
										.getWoDConfiguration()
								);
						
						try {
							XML_Manager xmlManager = new XML_Manager();
							Document document = xmlManager.createNewDocument();
							xmlManager.saveXMLElementToFile(
									woDApplicationData.getWoDConfiguration().get_XML_Element(document), 
									Configuration_Filename);

							get_Composite_GameMenu().show_Main();
						} catch (Exception e) {
							show_Error(e.getMessage());
						}
					}				

				}else
				{
					woDApplicationData.setWoDConfiguration(
							get_Composite_GameMenu()
								.get_Composite_Configuration()
									.getWoDConfiguration()
							);
					
					try {
						XML_Manager xmlManager = new XML_Manager();
						Document document = xmlManager.createNewDocument();
						xmlManager.saveXMLElementToFile(
								woDApplicationData.getWoDConfiguration().get_XML_Element(document), 
								Configuration_Filename);

						get_Composite_GameMenu().show_Main();
					} catch (Exception e) {
						show_Error(e.getMessage());
					}
				}
									
			} catch (Exception e) {
				// TODO Auto-generated catch block
				show_Error("Configuración de servidor Web no válida.");
				get_Composite_GameMenu().get_Composite_Configuration().show_Configuration_Connection_Error();
			}
			
			
			break;

		default:
			break;
		}
		
	}
	
	private Composite_GameRoom get_Composite_GameRoom(Composite_Options_Listener listener)
	{
		if (compositeGameRoom == null)
		{
			GridData gridData = new GridData();
			gridData.grabExcessHorizontalSpace = true;
			gridData.grabExcessVerticalSpace = true;
			gridData.horizontalAlignment = SWT.CENTER;
			gridData.verticalAlignment = SWT.CENTER;
			
			compositeGameRoom = new Composite_GameRoom(shell, SWT.NONE);
		
			compositeGameRoom.setLayoutData(gridData);
			
			compositeGameRoom.get_Composite_Options().add_Composite_Options_Listener(listener);
			
		}
		
		return compositeGameRoom;
	}
	

	@Override
	public void on_Composite_Options_Changed(Composite_Options_Event event) {
	
		switch (event.getEventType()) {
		case Composite_Options_Event.Event_Types.EXIT:
			try {
				
				manage_EXIT_EVENT(); //primero enviamos nuestra baja de partida a la web
				woDGameManager.getWoDP2PPeer().send_Leave_Game();		
				
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				Thread.currentThread().sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			compositeGameRoom.dispose();
			compositeGameRoom = null;
			show_GameMenu();
			
			break;

		case Composite_Options_Event.Event_Types.GAME_RT_START:

			final long ts_Start = (Long) event.getData();
//			final WoD_Application woDApplication = this;
			
			Runnable runnable = new Runnable() {
				
				
				
				@Override
				public void run() {

					compositeGameRoom.dispose();
					compositeGameRoom = null;
					
					get_Composite_RT_Game(ts_Start);
					
//					shell.setLayout(new FillLayout());
//					
//					compositeRTGame = new Composite_RT_Game(
//							shell, 
//							SWT.NONE,
//							woDGameManager.getWoDP2PPeer().get_My_WoD_Peer(),
//							woDGameManager.getWoDP2PPeer().getWoDClientRT(),
//							woDGameManager.getWoDP2PPeer().getWoDClientPeersList(),
//							ts_Start,
//							woDGameManager.getWoDP2PPeer().getOffset(),
//							woDApplicationData.getWoDGame().getMap_Name());
//
//					
//					
//					woDGameManager.getWoDP2PPeer().getWoDClientRT().add_WoD_Client_RT_Listener(
//							compositeRTGame.get_Map_Board()
//							);
//					compositeRTGame.get_Map_Board().add_WoD_MapBoard_Listener(
//							woDGameManager.getWoDP2PPeer());
//
//					compositeRTGame.get_Map_Board().add_WoD_MapBoard_Listener(woDApplication);
//					
//					
//
//					shell.pack();
				}
			};
			
			display.asyncExec(runnable);
			
			
			Runnable runnableMusicaPartida = new Runnable() {
				
				@Override
				public void run() {
					//PlaySoundStream.iniciaMusicaPartida("http://147.83.115.29:8080/wod/partida.mp3");
					PlaySoundStream.iniciaMusicaPartida("http://" +
							woDApplicationData.getWoDConfiguration().getWeb_Server() + ":" +  woDApplicationData.getWoDConfiguration().getWeb_Server_Port() +
							"/partida.mp3");
				}
			};
			
			
			/**
			 * Music
			 */
			Thread thread_MusicaPartida = new Thread(runnableMusicaPartida);
			thread_MusicaPartida.setDaemon(true);
			thread_MusicaPartida.start();
			
			
			break;
			
		default:
			break;
		}

	}
	
	public void set_ShowMode(final Display disp)
	{
		Runnable runnable = new Runnable() {
		
		@Override
		public void run() {
			
			disp.syncExec(new Runnable() {
				
				@Override
				public void run() {
					if (woDApplicationData.getMode() == WoD_Application_Data.Mode.LAN){
						get_Composite_GameMenu().get_Composite_Main().getButton_ShowGames().setEnabled(false);
					}
					else{
						get_Composite_GameMenu().get_Composite_Main().getButton_ShowGames().setEnabled(true);
					}
					
				}
			});
						
		}
	};
	
	new Thread(runnable).start(); 		
	

	}
	

	private Composite_RT_Game get_Composite_RT_Game(long ts_Start)
	{
		if (compositeRTGame == null)
		{
			shell.setLayout(new FillLayout());
			
			compositeRTGame = new Composite_RT_Game(
					shell, 
					SWT.NONE,
					woDGameManager.getWoDP2PPeer().get_My_WoD_Peer(),
					woDGameManager.getWoDP2PPeer().getWoDClientRT(),
					woDGameManager.getWoDP2PPeer().getWoDClientPeersList(),
					ts_Start,
					woDGameManager.getWoDP2PPeer().getOffset(),
					woDApplicationData.getWoDGame().getMap_Name());

			
			
			woDGameManager.getWoDP2PPeer().getWoDClientRT().add_WoD_Client_RT_Listener(
					compositeRTGame.get_Map_Board()
					);
			compositeRTGame.get_Map_Board().add_WoD_MapBoard_Listener(
					woDGameManager.getWoDP2PPeer());

			compositeRTGame.get_Map_Board().add_WoD_MapBoard_Listener(this);
			
			

			shell.pack();
		}
		
		return compositeRTGame;
	}
	
	@Override
	public void on_Composite_List_Games_Changed(Composite_List_Games_Event event) {
		switch (event.getEventType()) {
		case Composite_List_Games_Event.Event_Types.CONNECT_TO_GAME:
			
			woDApplicationData.setWoDGame(new WoD_Game());
			woDApplicationData.getWoDGame().setServerHost(
					compositeGameMenu
						.get_composite_List_Games()
							.getText_Peer_Host()
					);
			
			woDApplicationData.getWoDGame().setServer_port(
					Integer.valueOf(					
						compositeGameMenu
						.get_composite_List_Games()
						.getText_Peer_Port())
					);
			
			compositeGameMenu.dispose();
			compositeGameMenu = null;
			
			get_Composite_GameRoom(this);
			shell.setSize(new Point(500, 460));
			woDApplicationData.setState(WoD_Application_Data.State.GAME_ROOM);
			
			Runnable runnable = new Runnable() {
				
				@Override
				public void run() {
					try {
						woDGameManager = new WoD_Game_Manager(woDApplicationData, compositeGameRoom);
					} catch (Exception e) {
						show_Error(e.getMessage());
					}
					
				}
			};
			
			display.asyncExec(runnable);

			break;

		default:
			break;
		}

	}

	public void manage_EXIT_EVENT() throws Exception
	{
		if(woDGameManager.getWoDP2PPeer().isIam_Root() && woDApplicationData.getMode() == WoD_Application_Data.Mode.WAN)
		{
			ArrayList<String> PlayerNames = new ArrayList<String>();

			for (WoD_Peer Peer : woDGameManager.getWoDP2PPeer().getWoDClientPeersList().getWoD_Peers())
			{
				PlayerNames.add(Peer.getUserName());
				System.out.println("\n QUICKING PEER NAME: " + Peer.getUserName());
			}	
			WoD_InfoPartidasActuales wipa = WoD_HttpMessage.GetCurrentPlayersOnGame(
					woDApplicationData.getWoDConfiguration().getWeb_Server(),
					woDApplicationData.getWoDConfiguration().getWeb_Server_Port(), 
					String.valueOf(woDApplicationData.getWoDGame().getID_Game()));

			if (Integer.parseInt(wipa.getPlayersNumber())==1)
			{
				PlayerNames.clear();
				try {
					//SE PIRA EL ROOT Y NO QUEDA MÁS GENTE EN LA SALA. PARTIDA FINALIZADA
					WoD_HttpMessage.UpdateGame(
							woDApplicationData.getWoDConfiguration().getWeb_Server(), 
							woDApplicationData.getWoDConfiguration().getWeb_Server_Port(), 
							woDApplicationData.getWoDPlayerData().getUserName(), 
							woDApplicationData.getWoDGame().getServerHost(), 
							String.valueOf(woDApplicationData.getWoDGame().getServer_port()), 
							"0", 
							String.valueOf(woDApplicationData.getWoDGame().getID_Game()), 
							woDApplicationData.getWoDGame().getGame_Title(), 
							PlayerNames
							);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					show_Error(e.getMessage());
				}
				
			}else
			{
				try {
					//SE PIRA EL ROOT Y SIGUE QUEDANDO GENTE EN LA PARTIDA. EL NUEVO ROOT ENVIARÁ UPDATE CON LA NUEVA INFORMACIÓN DE PARTIDA.
					System.out.println("\n FROM WOD_APPLICATION");
					WoD_HttpMessage.UpdateGame
							(
							woDApplicationData.getWoDConfiguration().getWeb_Server(), 
							woDApplicationData.getWoDConfiguration().getWeb_Server_Port(), 
							woDApplicationData.getWoDPlayerData().getUserName(), 
							woDApplicationData.getWoDGame().getServerHost(), 
							String.valueOf(woDApplicationData.getWoDGame().getServer_port()), 
							"1", 
							String.valueOf(woDApplicationData.getWoDGame().getID_Game()), 
							woDApplicationData.getWoDGame().getGame_Title(), 
							PlayerNames
							);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					show_Error(e.getMessage());
				}
			}
		}	
		
	}
	

	@Override
	public void on_WoD_MapBoard_Change(WoD_MapBoard_Event event) {
		
		
		final WoD_Application woDApplication = this;
		switch (event.getEvent_Type()) {
		
		
		
		case WoD_MapBoard_Event.Event_Types.CAPTAIN_CAPTURED:
			
			
			Runnable runnable_CAPTAIN_CAPTURED = new Runnable() {
				
				@Override
				public void run() {
					show_Info("Capitán capturado");
					
					//compositeRTGame.get_Map_Board().dispose();
					
					
					compositeRTGame.dispose();
					
					woDApplicationData.getWoDGame().setGame_State(WoD_Game.Game_States.Game_Room);
					
					shell.setSize(new Point(500, 400));
					shell.setLayout(new GridLayout());
					
					get_Composite_GameRoom(woDApplication);

					shell.pack();
					//compositeRTGame = null;
				}
			};
			
//			display.asyncExec(runnable_CAPTAIN_CAPTURED);
			if(woDApplicationData.getMode() == WoD_Application_Data.Mode.WAN)
            {
                    ArrayList<WoD_InfoJugadoresPartida> players = new ArrayList<WoD_InfoJugadoresPartida>();
                                                                    
                    for(WoD_Peer peer : woDGameManager.getWoDP2PPeer().getWoDClientPeersList().getWoD_Peers())
                    {
                            WoD_InfoJugadoresPartida player = new WoD_InfoJugadoresPartida();
                            player.setPlayerName(peer.getUserName());
                            
                            if(peer.getTeam() == WoD_Game.Game_Teams.Captain_Team)
                                    player.setRole("2");
                            else
                                    player.setRole("1");

                            players.add(player);
                    }
                    
                    try {
                            WoD_HttpMessage.SetStats(woDApplicationData.getWoDConfiguration().getWeb_Server(), 
                                            String.valueOf(woDApplicationData.getWoDConfiguration().getWeb_Server_Port()), 
                                            String.valueOf(woDApplicationData.getWoDGame().getID_Game()), 
                                            "1", 
                                            players);
                    } catch (Exception e) {
                            // TODO Auto-generated catch block
                            System.out.println("HTTP error connection. Stats can't be updated.");
                    }                                       
            }

			
			
			show_Info("Capitán capturado");
			PlaySoundStream.detenerMusica();
			compositeRTGame.dispose();
			
			woDApplicationData.getWoDGame().setGame_State(WoD_Game.Game_States.Game_Room);
			
			shell.setSize(new Point(500, 400));
			shell.setLayout(new GridLayout());
			get_Composite_GameRoom(woDApplication);

			shell.pack();
			
			System.exit(0);
			
			
			break;
			
			
		case WoD_MapBoard_Event.Event_Types.CAPTAIN_WINS:
			
			
			Runnable runnable_CAPTAIN_WINS = new Runnable() {
				
				@Override
				public void run() {
					show_Info("Capitán gana");
					
					compositeRTGame.dispose();
					
					woDApplicationData.getWoDGame().setGame_State(WoD_Game.Game_States.Game_Room);
					
					shell.setSize(new Point(500, 400));
					shell.setLayout(new GridLayout());
					get_Composite_GameRoom(woDApplication);

					shell.pack();
					//compositeRTGame = null;
				}
			};
//			display.asyncExec(runnable_CAPTAIN_WINS);
			if(woDApplicationData.getMode() == WoD_Application_Data.Mode.WAN)
            {
                    ArrayList<WoD_InfoJugadoresPartida> players = new ArrayList<WoD_InfoJugadoresPartida>();
                                                                    
                    for(WoD_Peer peer : woDGameManager.getWoDP2PPeer().getWoDClientPeersList().getWoD_Peers())
                    {
                            WoD_InfoJugadoresPartida player = new WoD_InfoJugadoresPartida();
                            player.setPlayerName(peer.getUserName());
                            
                            if(peer.getTeam() == WoD_Game.Game_Teams.Captain_Team)
                                    player.setRole("2");
                            else
                                    player.setRole("1");

                            players.add(player);
                    }
                    
                    try {
                            WoD_HttpMessage.SetStats(woDApplicationData.getWoDConfiguration().getWeb_Server(), 
                                            String.valueOf(woDApplicationData.getWoDConfiguration().getWeb_Server_Port()), 
                                            String.valueOf(woDApplicationData.getWoDGame().getID_Game()), 
                                            "2", 
                                            players);
                    } catch (Exception e) {
                            // TODO Auto-generated catch block
                            System.out.println("HTTP error connection. Stats can't be updated.\n" +
                                            "IP WEB SERVER: " + woDApplicationData.getWoDConfiguration().getWeb_Server() + 
                                            "\nCONTROL PORT: " + String.valueOf(woDApplicationData.getWoDConfiguration().getWeb_Server_Port()) + 
                                            "\nGAME ID: " + String.valueOf(woDApplicationData.getWoDGame().getID_Game()));
                    }                                       
            }

			
			show_Info("Capitán gana");
			PlaySoundStream.detenerMusica();
			compositeRTGame.dispose();
			
			
			woDApplicationData.getWoDGame().setGame_State(WoD_Game.Game_States.Game_Room);
			
			shell.setSize(new Point(500, 400));
			shell.setLayout(new GridLayout());
			get_Composite_GameRoom(woDApplication);

			shell.pack();
			
			System.exit(0);
			break;			

		default:
			break;
		}
		
	}
	

	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
	
		if (args.length > 0)
		{
			new WoD_Application(args[0]).execute();
		}
		else
		{
			new WoD_Application().execute();
		}

	}
	
}
